package ch.jhc.sevlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import ch.jhc.Global;
import ch.jhc.bean.Article;
import ch.jhc.bean.User;
import ch.jhc.db.ArticleDao;

@WebServlet("/admin/add.do")
public class AddServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException{
		//request.setCharacterEncoding("UTF-8");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		int userId = request.getIntHeader("userId");
		
		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setPublishDate(new Date());
		article.setUserId(userId);
		
		User user = (User) request.getSession().getAttribute(Global.CURRENT_USER);
		article.setUserId(user.getId());
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		try {
			ArticleDao.add(runner, article);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(500);
		}
		
		response.sendRedirect("userlist.do");
		
	}
}
